package com.ymx.quanjuhe;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ymx.quanjuhe.bean.VisitLog;
import com.ymx.quanjuhe.dao.VisitLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;

import static org.springframework.http.HttpHeaders.USER_AGENT;

public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    RestTemplate restTemplate;

    VisitLogMapper visitLogMapper;

    public SessionInterceptor(VisitLogMapper visitLogMapper) {
        this.visitLogMapper = visitLogMapper;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        InDB(request);
        return true;
    }

    @Async
    public void InDB(HttpServletRequest request) {
        VisitLog visitLog = new VisitLog();
        String ipAddr = getIpAddr(request);
        visitLog.setVisitIp(ipAddr);
//        ObjectMapper
//        'http://ip.taobao.com/service/getIpInfo.php?ip='+ipAddr
//        restTemplate.getForObject()
        visitLog.setVisitAddress(request.getContextPath());
        visitLog.setVisitTime(new Date());
        visitLog.setVisitBrowser(request.getHeader(USER_AGENT));
        int insert = visitLogMapper.insert(visitLog);
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }


}